# -*- coding:UTF-8 -*-
# 虽然没有想好这个类有什么用，但是暂时先放入这些功能性的方法
import os
import requests
import time

class FileHelper(object):
    """description of class"""
    
    def __init__(self, path="./files/init.xml"):
        self.path = path
    
    def download_xml(self, ip, port, key, im_name):
        params_data = {"imId": im_name, "initKey": key, "imIp": ip, "imPort": port}
        while True:
            print("Request params:{}".format(params_data))
            from init.fileinit import url_file as ready_file
            r = requests.get(ready_file, params=params_data,stream=True)
            if r.status_code == 200:
                with open(self.path, "wb") as f:
                    for chunk in r.iter_content(chunk_size=512):
                        if chunk:
                            f.write(chunk)
                break
            else:
                print("web服务器地址错误，请检查")
                
            time.sleep(1.5)
        return self.path
    
    def set_path(self, path):
        self.path = path
        return
    
    # 如果没有这个路径怎么处理——>应该修改，当return 为warning时，应该将loop修改为false
    # 打开和关闭成为独立的命令
    def command(self, cmd, path, data):
        if cmd == "a" or cmd == "add" or cmd == "creat":
            try:
                os.open(path, "rw")
            except:
                return "warning"
            finally:
                os.close(path)
        elif cmd == "o" or cmd == "open":
            
            try:
                os.open(path, "rw")
            except:
                return "warning"
            finally:
                return "ok"
        elif cmd == "d" or cmd == "del" or cmd == "delete" or cmd == "remove":
            try:
                os.remove(path, "rw")
            except:
                return "warning"
            finally:
                return "ok"
        elif cmd == "w" or cmd == "write" or cmd == "update":
            try:
                os.write(path, "rw")
            except:
                return "warning"
            finally:
                os.close(path)
        elif cmd == "r" or cmd == "replace":
            try:
                os.remove(path)
                os.open(path, "rw")
                os.write(path, data)
            except:
                return "warning"
            finally:
                os.close(path)
        elif cmd == 'c' or cmd == "close":
            try:
                os.remove(path)
                os.open(path, "rw")
                os.write(path, data)
            except:
                return "warning"
            finally:
                os.close(path)
